package xyz.mumuwei.youthcourseserver.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import xyz.mumuwei.youthcourseserver.common.dto.PageDto;
import xyz.mumuwei.youthcourseserver.common.dto.UserDto;
import xyz.mumuwei.youthcourseserver.common.lang.Const;
import xyz.mumuwei.youthcourseserver.common.lang.Result;
import xyz.mumuwei.youthcourseserver.pojo.User;
import xyz.mumuwei.youthcourseserver.pojo.UserInfo;
import xyz.mumuwei.youthcourseserver.service.UserInfoService;
import xyz.mumuwei.youthcourseserver.service.UserService;
import xyz.mumuwei.youthcourseserver.service.WechatService;

import javax.validation.constraints.NotBlank;
import java.util.List;

/**
 * @author mumuwei
 * @since 2022-02-19
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {
    final UserService userService;
    final UserInfoService userInfoService;
    final WechatService wechatService;

    /**
     * 根据 token获取用户信息
     */
    @GetMapping
    public Result getUserInfoByToken(@RequestAttribute Integer uid){
        return userService.userInfoByTokenId(uid);
    }

    /**
     * 根据用户id 修改获取用户信息
     */
    @GetMapping("/{id}")
    public Result getUserInfoById(@PathVariable("id") Integer id){
        return userService.userInfoByUserId(id);
    }

    /**
     * 根据 token 获取id 更新信息
     */
    @PostMapping("/update")
    public Result updateUserByTokenId(@RequestAttribute Integer uid, UserDto userDto){
        userDto.setId(uid);
       if (updateUser(userDto)){
           return Result.success("更新成功");
       }
        return Result.fail("请先绑定手机号码");
    }

    /**
     * 根据用户信息id更新用户信息
     * @param userInfo 用户信息
     */
    @PostMapping("/update/admin")
    public Result updateAdminUserInfo(@Validated UserInfo userInfo){
        boolean update = userInfoService.updateById(userInfo);
        if(update){
            return Result.success("更新信息成功！");
        }
        return Result.fail("更新信息失败！");
    }

    /**
     * 管理员 根据用户id 修改用户信息
     */
    @PostMapping("/update_u")
    public Result updateUserByUserId(UserDto userDto){
        if(userDto.getId() != null){
            boolean flag = updateUser(userDto);
            if(userDto.getState() != null){
                User user = new User();
                user.setId(userDto.getId());
                user.setState(userDto.getState());
                userService.updateById(user);
                flag = true;
            }
            if(flag){
                return Result.success("更新成功");
            }
        }
        return Result.fail("参数格式有误");
    }

    /**
     * 根据用户id删除用户，只删除user表
     */
    @GetMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id){
        boolean flag = userService.removeById(id);
        if(flag){
            return Result.success("删除成功！");
        }
        return Result.fail("删除失败！");
    }

    /**
     * 根据用户信息 id删除用户信息
     * @param id UserInfo的 id
     */
    @GetMapping("/delete/info/{id}")
    public Result deleteUserInfo(@PathVariable Integer id){
        boolean b = userInfoService.removeById(id);
        if(b){
            return Result.success("删除成功！");
        }
        return Result.fail("删除失败！");
    }

    /**
     * 获取用户按角色-分页
     * @param pageDto 分页参数
     * @param roleId 角色id
     */
    @GetMapping("/page")
    public Result getUserInfoPage(PageDto pageDto, Integer roleId){
        IPage<UserInfo> page = userService.getUserInfoPage(pageDto, roleId);
        if(page == null){
            return Result.fail("查询失败!");
        }
        return Result.success(page);
    }

    /**
     * 获取用户按角色-不分页
     * @param roleId 角色id
     */
    @GetMapping("/list")
    public Result getUserInfoList(Integer roleId){
        List<UserInfo> list = userService.getUserInfoList(roleId);
        if(list == null){
            return Result.fail("查询失败！");
        }
        return Result.success(list);
    }

    /**
     * 管理员创建用户——指定角色
     * @param userInfo 角色信息
     */
    @PostMapping("/create")
    public Result createUserInfo(@Validated UserInfo userInfo){
        if( userInfo.getRoleId() == null || userInfo.getRoleId() == 0){
            // 默认学生
            userInfo.setRoleId(Const.STUDENT_ROLE_CODE);
        }
        Integer info = userInfoService.createInfo(userInfo);
        if(info == -1){
            return Result.fail("创建失败，手机号码已被绑定！");
        }
        if(info > 0){
            return Result.success("创建成功！");
        }
        return Result.fail("创建失败！");
    }

    @PostMapping("/updatePass")
    public Result updatePass(@RequestAttribute Integer uid, String password, String newPass){
        if (userService.getById(uid).getKeyword().equals(password)) {
            User user = new User();
            user.setId(uid);
            user.setKeyword(newPass);
            boolean update = userService.updateById(user);
            if(update) {
                return Result.success("密码修改成功！");
            } else {
                return Result.fail("密码修改失败！");
            }
        }
        return Result.fail("密码错误");
    }

    /**
     * 判断参数是否为空字符串或null
     * @return ture value不为null或空串
     */
    private boolean validStrNull(String value){
        return !("".equals(value) || value == null);
    }

    private boolean updateUser(UserDto userDto){
        boolean isUpdate = false;
        // 查询用户是否绑定手机号
        if (!"".equals(userDto.getPhone())) {
            UserInfo one = userInfoService.getOne(new QueryWrapper<UserInfo>().eq("user_id", userDto.getId()));
            if (one == null || "".equals(one.getPhone())) {
                return false;
            }
        }
        // 更新真实姓名
        if(validStrNull(userDto.getRealName())){
            UserInfo userInfo = new UserInfo();
            userInfo.setRealName(userDto.getRealName());
            userInfoService.update(userInfo,new UpdateWrapper<UserInfo>().eq("user_id", userDto.getId()));
            isUpdate = true;
        }

        boolean flag = false;
        User user = new User();
        user.setId(userDto.getId());
        if(validStrNull(userDto.getOpenId())){
            user.setOpenId(userDto.getOpenId());
            flag = true;
        }
        if(validStrNull(userDto.getUsername()) && userDto.getUsername().length() > Const.USERNAME_MIN_SIZE){
            user.setUsername(userDto.getUsername());
            flag = true;
        }
        if(validStrNull(userDto.getKeyword()) && userDto.getKeyword().length() > Const.USERNAME_MIN_SIZE){
            user.setKeyword(userDto.getKeyword());
            flag = true;
        }
        if(validStrNull(userDto.getEmail())){
            user.setEmail(userDto.getEmail());
            flag = true;
        }
        if(validStrNull(userDto.getPhone())){
            user.setPhone(userDto.getPhone());
            flag = true;
        }
        if(flag){
            userService.updateById(user);
            isUpdate = true;
        }
        return isUpdate;
    }

    /**
     * 绑定微信
     */
    @GetMapping("/wechat/band/{code}")
    public Result bandWechat(@PathVariable @NotBlank(message = "状态码不能为空") String code, @RequestAttribute Integer uid) throws Exception {
        return wechatService.bandWechat(code, uid);
    }

    /**
     * 解绑微信
     * @param uid 用户Id
     * @return 解绑结果
     */
    @GetMapping("/wechat/unbind")
    public Result unBandWechat(@RequestAttribute Integer uid) {
        User user = new User();
        user.setId(uid);
        user.setOpenId("");
        boolean update = userService.updateById(user);
        if (update) {
            return Result.success("解绑成功");
        }
        return Result.fail("解绑失败");
    }

    /**
     * 更新用户绑定手机号
     * @param uid 用户id
     * @param phone 手机号
     * @param code 验证码
     * @return 更新结果
     */
    @PostMapping("/updatePhone")
    public Result updateUserPhone(@RequestAttribute Integer uid, String phone, String code){
        return userService.updateUserPhone(uid, phone, code);
    }

    /**
     * 分页查询账户信息
     * @param pageDto 分页参数
     * @return 用户账户列表
     */
    @GetMapping("/account/page")
    public Result getUserAccountPage(PageDto pageDto){
        return userService.getUserPage(pageDto);
    }

    /**
     * 获取系统账户列表
     * @return 账户列表
     */
    @GetMapping("/account/list")
    public Result getUserAccountList(){
        return userService.getUserList();
    }

    /**
     * 修改用户账户状态
     * @param id 用户账户id
     * @return 操作结果
     */
    @GetMapping("/state/{id}")
    public Result updateUserState(@PathVariable Integer id) {
        User user = userService.getById(id);
        user.setState(user.getState()==0?1:0);
        userService.updateById(user);
        return Result.success("更新状态成功");
    }

    /**
     * 首页获取近期用户日活数
     */
    @GetMapping("/dailyLife")
    public Result getDailyLife() {
        return userService.getDailyLife();
    }
}

